package com.gitee.qdbp.general.mgr.controller.personnel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.jdbc.ordering.OrderPaging;
import com.gitee.qdbp.able.jdbc.paging.PageList;
import com.gitee.qdbp.able.jdbc.paging.Paging;
import com.gitee.qdbp.able.result.ResponseMessage;
import com.gitee.qdbp.base.controlling.IDataIsolationControlling;
import com.gitee.qdbp.base.enums.Gender;
import com.gitee.qdbp.base.enums.OperateType;
import com.gitee.qdbp.base.system.model.IAccount;
import com.gitee.qdbp.base.utils.EnumTools;
import com.gitee.qdbp.base.utils.SessionTools;
import com.gitee.qdbp.general.system.api.permission.model.RoleCoreBean;
import com.gitee.qdbp.general.system.api.permission.model.RoleCoreWhere;
import com.gitee.qdbp.general.system.api.permission.service.IRoleCoreQueryer;
import com.gitee.qdbp.general.system.api.personnel.model.DepartmentCoreBean;
import com.gitee.qdbp.general.system.api.personnel.model.DepartmentCoreWhere;
import com.gitee.qdbp.general.system.api.personnel.model.UserCoreBean;
import com.gitee.qdbp.general.system.api.personnel.model.UserCoreUpdate;
import com.gitee.qdbp.general.system.api.personnel.model.UserCoreWhere;
import com.gitee.qdbp.general.system.api.personnel.service.IDepartmentCoreQueryer;
import com.gitee.qdbp.general.system.api.personnel.service.IUserCoreExecutor;
import com.gitee.qdbp.general.system.api.personnel.service.IUserCoreQueryer;
import com.gitee.qdbp.general.system.api.personnel.service.IUserManageExecutor;
import com.gitee.qdbp.general.system.enums.UserSource;
import com.gitee.qdbp.general.system.enums.UserState;
import com.gitee.qdbp.tools.utils.ConvertTools;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * 账户增删改查基础控制器
 *
 * @author zhaohuihua
 * @version 170401
 */
@Controller
@RequestMapping("actions/account-crud/mamager")
public class AccountCrudController {

    @Autowired
    private IUserCoreQueryer userCoreQueryer;
    @Autowired
    private IUserCoreExecutor userCoreExecutor;
    @Autowired
    private IUserManageExecutor userManageExecutor;
    @Autowired
    private IRoleCoreQueryer roleCoreQueryer;
    @Autowired
    private IDepartmentCoreQueryer departmentCoreQueryer;
    @Autowired
    private IDataIsolationControlling dataIsolationControlling;

    /**
     * 查询部门列表
     *
     * @param paging 分页信息
     * @param model 查询条件
     * @return 部门列表
     */
    @ResponseBody
    @RequestMapping("dept/list")
    @RequiresPermissions("account-crud:mamager:query")
    public ResponseMessage list(DepartmentCoreWhere model, OrderPaging paging, Boolean extra) {
        try {
            PageList<DepartmentCoreBean> list = departmentCoreQueryer.list(model, paging);
            ResponseMessage result = new ResponseMessage(list.toList());
            return result;
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /**
     * 查询管理员信息
     *
     * @param id ID
     * @return 管理员信息
     */
    @ResponseBody
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @RequiresPermissions("account-crud:mamager:query")
    public ResponseMessage find(@PathVariable("id") String id) {
        try {
            UserCoreBean user = userCoreQueryer.find(id);
            user.setPassword(null); // 清空密码
            return new ResponseMessage(user);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /**
     * 查询管理员信息
     *
     * @param account 工号/手机/邮箱
     * @return 管理员信息
     */
    @ResponseBody
    @RequestMapping(value = "myinfo", method = RequestMethod.GET)
    @RequiresPermissions("account-crud:mamager:query")
    public ResponseMessage myinfo() {
        try {
            IAccount admin = SessionTools.getLoginUser();
            return new ResponseMessage(admin);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /**
     * 查询管理员列表
     *
     * @param paging 分页信息
     * @param model 查询条件
     * @return 管理员列表
     */
    @ResponseBody
    @RequestMapping("list")
    @RequiresPermissions("account-crud:mamager:query")
    public ResponseMessage list(UserCoreWhere model, OrderPaging paging, Boolean extra) {
        try {
            dataIsolationControlling.handle(model, OperateType.QUERY, "tenantCode");

            PageList<UserCoreBean> list = userCoreQueryer.list(model, paging);
            for (UserCoreBean bean : list) {
                bean.setPassword(null); // 清空密码
            }
            ResponseMessage result = new ResponseMessage(list.toList());

            if (Boolean.TRUE.equals(extra)) {
                Map<String, ?> map = EnumTools.getEnumsResource(Gender.class, UserState.class);
                result.addExtra(map);
                // 查询角色列表
                RoleCoreWhere where = new RoleCoreWhere();
                if (!SessionTools.isDevelopMode()) {
                    where.setDefaults(false); // 只有开发模式才允许查询默认角色
                }
                OrderPaging p = OrderPaging.of(Paging.NONE, "sortIndex asc, createTime desc");
                List<RoleCoreBean> roles = roleCoreQueryer.list(where, p).toList();
                result.addExtra("Role", roles);
            }
            // 查询用户角色关联表
            if (VerifyTools.isNotBlank(list)) {
                List<String> userIds = new ArrayList<>();
                for (UserCoreBean user : list) {
                    userIds.add(user.getId());
                }
                Map<String, List<RoleCoreBean>> refTemp = roleCoreQueryer.listByUserIds(userIds);
                Map<String, List<String>> refMap = new HashMap<>();
                for (Map.Entry<String, List<RoleCoreBean>> entry : refTemp.entrySet()) {
                    List<String> roleIds = new ArrayList<>();
                    for (RoleCoreBean role : entry.getValue()) {
                        roleIds.add(role.getId());
                    }
                    refMap.put(entry.getKey(), roleIds);
                }
                result.addExtra("RoleIds", refMap);
            }
            return result;
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 创建管理员 **/
    @ResponseBody
    @RequestMapping("create")
    @RequiresPermissions("account-crud:mamager:create")
    public ResponseMessage create(UserCoreBean model, String[] roleIds) {
        model.setUserSource(UserSource.INPUT);
        try {
            IAccount operator = SessionTools.getLoginUser();
            userCoreExecutor.create(model, ConvertTools.toList(roleIds), operator);
            return new ResponseMessage(model);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 修改管理员 **/
    @ResponseBody
    @RequestMapping("update")
    @RequiresPermissions("account-crud:mamager:update")
    public ResponseMessage update(UserCoreUpdate model, String[] roleIds) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            userCoreExecutor.update(model, ConvertTools.toList(roleIds), operator);
            return new ResponseMessage(model);
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 锁定管理员 **/
    @ResponseBody
    @RequestMapping("disable")
    @RequiresPermissions("account-crud:mamager:disable")
    public ResponseMessage disable(String id) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            userManageExecutor.disable(id, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 解锁管理员 **/
    @ResponseBody
    @RequestMapping("enable")
    @RequiresPermissions("account-crud:mamager:enable")
    public ResponseMessage enable(String id) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            userManageExecutor.enable(id, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 重置管理员密码 **/
    @ResponseBody
    @RequestMapping("password")
    @RequiresPermissions("account-crud:mamager:password")
    public ResponseMessage password(String id, String password) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            userManageExecutor.resetPassword(id, password, operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

    /** 删除管理员 **/
    @ResponseBody
    @RequestMapping("delete")
    @RequiresPermissions("account-crud:mamager:delete")
    public ResponseMessage delete(String[] ids) {

        try {
            IAccount operator = SessionTools.getLoginUser();
            userCoreExecutor.delete(ConvertTools.toList(ids), operator);
            return new ResponseMessage();
        } catch (ServiceException e) {
            return new ResponseMessage(e);
        }
    }

}
